package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.ArticleCommentDTO;
import com.sky.dto.BackstageCommentDeleteDTO;
import com.sky.dto.BackstageCommentQueryDTO;
import com.sky.mapper.BackstageCommentMapper;
import com.sky.result.PageResult;
import com.sky.service.BackstageCommentService;
import com.sky.vo.AnnouncementsVO;
import com.sky.vo.ArticleChildCommentVo;
import com.sky.vo.ArticleCommentsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 贾晓晨
 * @version 1.0
 */
@Service
public class BackstageCommentServiceImp implements BackstageCommentService {

    @Autowired
    private BackstageCommentMapper backstageCommentMapper;
    @Override
    public void deleteComment(List<Integer> ids) {
        backstageCommentMapper.deleteArticle(ids);
    }

    private ArticleCommentsVO buildCommentTree(List<ArticleCommentDTO> allComments, String articleId) {
        ArticleCommentsVO vo = new ArticleCommentsVO();
        vo.setArticleId(String.valueOf(articleId));

        // 创建映射：父评论ID → 子评论列表
        Map<Integer, List<ArticleCommentDTO>> childCommentMap = allComments.stream()
                .filter(c -> c.getHeadId() != null)
                .collect(Collectors.groupingBy(ArticleCommentDTO::getHeadId));

        // 处理顶级评论（headId为null）
        List<ArticleCommentsVO.CommentItem> commentItems = allComments.stream()
                .filter(c -> c.getHeadId() == null)
                .map(topComment -> {
                    ArticleCommentsVO.CommentItem item = new ArticleCommentsVO.CommentItem();
                    // 设置父评论信息
                    item.setId(topComment.getId());
                    item.setUserId(String.valueOf(topComment.getUserId()));
                    item.setNickName(topComment.getNickName());
                    item.setContent(topComment.getContent());
                    item.setContentImg(topComment.getContentImg());
                    item.setCreateTime(topComment.getCreateTime());
                    item.setAvatarUrl(topComment.getAvatarUrl());

                    // 处理子评论
                    List<ArticleChildCommentVo> childComments = childCommentMap.getOrDefault(topComment.getId(), Collections.emptyList())
                            .stream()
                            .map(child -> new ArticleChildCommentVo(
                                    child.getId(),
                                    String.valueOf(child.getUserId()),
                                    child.getNickName(),
                                    child.getAvatarUrl(),
                                    child.getContent(),
                                    child.getContentImg(),
                                    child.getParentName(),  // 被回复用户名称
                                    child.getCreateTime()
                            ))
                            .collect(Collectors.toList());

                    item.setChildComment(childComments);
                    return item;
                })
                .collect(Collectors.toList());

        vo.setCommentsList(commentItems);
        return vo;
    }

    @Override
    public PageResult getCommentList(BackstageCommentQueryDTO backstageCommentQueryDTO) {
        PageHelper.startPage(backstageCommentQueryDTO.getPage(), backstageCommentQueryDTO.getPageSize());
        List<ArticleCommentDTO> topComments = backstageCommentMapper.getTopComments(backstageCommentQueryDTO);
        Page<ArticleCommentDTO> page = (Page<ArticleCommentDTO>) topComments;

        List<Integer> topCommentIds = topComments.stream()
                .map(ArticleCommentDTO::getId)
                .collect(Collectors.toList());

        List<ArticleCommentDTO> allComments = new ArrayList<>(topComments);

        if (!topCommentIds.isEmpty()) {
            // 查询当前页顶级评论的子评论
            List<ArticleCommentDTO> childComments =
                    backstageCommentMapper.getChildCommentsByHeadIds(topCommentIds,backstageCommentQueryDTO.getSecondContent());
            allComments.addAll(childComments);
        }
        // 构建树形结构
        ArticleCommentsVO vo = buildCommentTree(allComments, String.valueOf(backstageCommentQueryDTO.getArticleId()));

        return new PageResult(page.getTotal(), vo.getCommentsList());
    }

    @Override
    public void deleteCommentByCommentId(List<Integer> ids) {
        // List<Integer> ids = backstageCommentDeleteDTO.getIds();
        // if (ids == null || ids.isEmpty()) {
        //     throw new IllegalArgumentException("评论ID列表不能为空");
        // }
        //
        // // 1. 分离出头部评论ID和子评论ID
        // List<Integer> headCommentIds = new ArrayList<>();
        // List<Integer> childCommentIds = new ArrayList<>();
        //
        // for (Integer id : ids) {
        //     ArticleCommentDTO comment = backstageCommentMapper.getCommentById(id);
        //     if (comment == null) {
        //         throw new RuntimeException("评论不存在: id=" + id);
        //     }
        //     if (comment.getHeadId() == null) {
        //         headCommentIds.add(id);
        //     } else {
        //         childCommentIds.add(id);
        //     }
        // }
        //
        // // 2. 删除子评论
        // if (!childCommentIds.isEmpty()) {
        //     backstageCommentMapper.batchDeleteCommentsByIds(childCommentIds);
        // }
        //
        // // 3. 删除头部评论及其子评论
        // if (!headCommentIds.isEmpty()) {
        //     // 先删除子评论
        //     backstageCommentMapper.batchDeleteChildCommentsByHeadIds(headCommentIds);
        //     // 再删除头部评论
        //     backstageCommentMapper.batchDeleteCommentsByIds(headCommentIds);
        // }
        backstageCommentMapper.batchDeleteCommentsByIds(ids);
    }

}


